import { NextRequest, NextResponse } from "next/server";
import { auth } from "@clerk/nextjs";
import { prisma } from "@/lib/prisma";

// 创建新聊天
export async function POST(req: NextRequest) {
  try {
    const { userId } = auth();

    // 检查用户认证
    if (!userId) {
      return NextResponse.json(
        { success: false, error: "未授权" },
        { status: 401 }
      );
    }

    const body = await req.json();
    const { knowledgeBaseId, title } = body;

    // 验证请求数据
    if (!knowledgeBaseId) {
      return NextResponse.json(
        { success: false, error: "知识库ID是必填项" },
        { status: 400 }
      );
    }

    // 检查知识库是否存在
    const knowledgeBase = await prisma.knowledgeBase.findUnique({
      where: { id: knowledgeBaseId },
    });

    if (!knowledgeBase) {
      return NextResponse.json(
        { success: false, error: "知识库不存在" },
        { status: 404 }
      );
    }

    // 检查是否是当前用户的知识库
    const user = await prisma.user.findUnique({
      where: { clerkId: userId },
    });

    if (!user || knowledgeBase.userId !== user.id) {
      return NextResponse.json(
        { success: false, error: "无权访问此知识库" },
        { status: 403 }
      );
    }

    // 创建新聊天
    const chat = await prisma.chat.create({
      data: {
        title: title || "新对话",
        knowledgeBaseId,
      },
    });

    return NextResponse.json({
      success: true,
      data: chat,
    });
  } catch (error) {
    console.error("创建聊天失败:", error);
    return NextResponse.json(
      { success: false, error: "创建聊天失败" },
      { status: 500 }
    );
  }
} 